-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local parser = {
    json_file = "",
}

local log = require "log"
local cjson = require "cjson"

function parser:new(obj, json_file, default_file)
    obj = obj or {}
    setmetatable(obj, self)
    self.__index = self
    self.json_file = json_file .. ".json"
    self.default_file = default_file
    return obj
end

function parser:read_file()
    local file, error_info = io.open(self.json_file, "r")
    if file == nil then
        file, error_info = io.open(self.default_file, "r")
        if file == nil then
            log:print(LOG_ERROR, "open file(%s) fail, %s", self.default_file, error_info)
            return false
        end
    end
    local str = file:read("*a")
    log:print(LOG_DEBUG, str)
    file:close()
    return true, str
end

function parser:parse()
    local ret, str = self:read_file()
    if ret then
        self.op_table = cjson.decode(str)
    end
    return ret
end

function parser:get_value(key)
    if self.op_table == nil then
        local ret = self:parse()
        if ret ~= true then
            log:print(LOG_DEBUG, "get value of key(%s) error", key)
            return
        end
    end
    return self.op_table[key]
end

function parser:set_value(key, value)
    if self.op_table == nil then
        local ret = self:parse()
        if ret ~= true then
            return
        end
    end
    self.op_table[key] = value
end

function parser:write_file()
    local str = cjson.encode(self.op_table)
    local file = io.open(self.json_file, "w")
    if file == nil then
        log:print(LOG_ERROR, "write_file open fiel fail")
        return
    end
    file:write(str)
    file:close()
end

return parser